import axios from 'axios';
import store from '@/store';
import router from '../router/index';
import bus from '@/utils/eventBus.js';
import { Toast } from 'vant';
var CryptoJS = require('crypto-js');

let host = `${window.location.origin}/apiV2`; // 生产环境加密接口地址
if (process.env.NODE_ENV === 'test') {
    // 测试
    host = `https://api-saas-test.sscanmou.com`;
} else if (process.env.NODE_ENV === 'uat') {
    //预发布环境
    host = 'https://saas-pre.sscanmou.com';
} else if (process.env.NODE_ENV === 'development') {
    // 开发 dev-开发环境接口地址  test-测试环境接口地址 product-生产环境接口地址
    // host = '/dev'; //开发环境
    host = '/test'; //测试环境
    // host = '/product'; //生产环境
}
const REQ_RETRY = 5; // 请求重试次数
const REQ_DELAY = 1000; // 请求重试间隔ms
const TIMEOUT = 120000; // 请求超时时间ms
// 创建实例
axios.defaults.isSetAuth = false; // 是否设置授权信息
const Axios = axios.create({
    baseURL: host,
    timeout: TIMEOUT,
    retry: REQ_RETRY, // 未实现
    retryDelay: REQ_DELAY, // 未实现
    headers: {
        // 'Content-Type': 'application/json;charset=UTF-8'
    }
});

// 请求拦截
Axios.interceptors.request.use(
    (request) => {
        // 未设置请求头则延迟请求
        if (!Axios.defaults.isSetAuth) {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve();
                }, 1000);
            }).then(function () {
                if (Axios.defaults.isSetAuth) {
                    request.headers.Authorization = Axios.defaults.headers.Authorization;
                }
                return request;
            });
        }
        return request;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截
Axios.interceptors.response.use(
    async (response) => {
        // 如果信息加密或者是字符串，则先解密或者反序列化为对象
        if (typeof response.data === 'string') {
            if (response.data.length > 0) {
                if (response.data[0] === '{') {
                    const output = JSON.parse(response.data);
                    response.data = output;
                } else {
                    // 新增AES解密
                    const key = CryptoJS.enc.Utf8.parse('f8db034bda44rtkb');
                    const bytes = CryptoJS.AES.decrypt(response.data, key, {
                        mode: CryptoJS.mode.ECB,
                        padding: CryptoJS.pad.Pkcs7
                    });
                    const outputStr = bytes.toString(CryptoJS.enc.Utf8);
                    const output = JSON.parse(outputStr);
                    response.data = output;
                }
            }
        }
        const okStatus = response.data.code == 0 || response.data.code == 200;
        const code = response.data.code;
        if (okStatus) {
            // 请求成功
            return Promise.resolve(response);
        } else {
            // 请求失败
            if (code === 401) {
                // 未登录或登录超时
                if (store.getters.token != '') {
                    await store.dispatch('user/logOut');
                }
                bus.emit('tdy-relogin', response.data || null); // 通过消息总线发送重登通知
                return Promise.reject(response);
            } else {
                // 其他请求失败情况
                Toast.fail({
                    message: response.data.msg || '服务器开小差了，请稍后刷新或联系项目经理进行反馈。',
                    forbidClick: true,
                    duration: 2000
                });
                setTimeout(() => {
                    router.push('/network');
                }, 280);
                return Promise.reject(response);
            }
        }
    },
    (error) => {
        Toast.fail({
            message: '服务器开小差了，请稍后刷新或联系项目经理进行反馈。',
            forbidClick: true,
            duration: 2000
        });
        setTimeout(() => {
            router.push('/network');
        }, 280);
        return Promise.reject(error);
    }
);

export default Axios;
